package com.shiva.oms.biz;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shiva.oms.logview.domain.ConnectCfg;

/**
 * 
 * 用户之前登录过的连接配置
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID    DATE            PERSON            REASON
 *  1     2018年4月23日         LA.01367604           Create
 * ****************************************************************************
 * </pre>
 * 
 * @author LA.01367604
 * @version 1.0
 */
public class HistoryConnRecordBiz extends AbstractCustomTemp<ConnectCfg> {

    private static final Logger logger = LoggerFactory.getLogger(HistoryFileRecordBiz.class);

    private static final String fileDir = "logv_conf";
    private static final String fileName = "history_conn.temp";
    private static final int MAX_KEEP = 5;
    private static final String ENTITY_SPLIT = ";";
    private static final String ENTITY_ATTR_SPLIT = ",";
    private File file = new File(CURRENT_DIR + FILE_SEP + fileDir + FILE_SEP + fileName);
    private List<ConnectCfg> connList;
    private static HistoryConnRecordBiz instance;

    private HistoryConnRecordBiz() {}

    public static HistoryConnRecordBiz getInstance() {
        if (instance == null) {
            instance = new HistoryConnRecordBiz();
        }
        return instance;
    }

    public List<ConnectCfg> getList() {
        if (connList == null) {
            connList = super.init(fileDir, fileName, file);
        }
        return connList;
    }

    public void addFileRec(ConnectCfg rec) {
        if (connList == null) {
            connList = super.init(fileDir, fileName, file);
        }
        connList = connList.stream().filter(data -> !data.equals(rec)).collect(Collectors.toList());
        connList.add(rec);
        if (connList.size() > MAX_KEEP) {// 超过最大记录数则删除最早的记录
            connList.remove(0);
        }
        super.saveAll(connList, file);
    }

    @Override
    protected String transList2Str(List<ConnectCfg> list) {
        return list.stream().map(ConnectCfg::toString).collect(Collectors.joining(ENTITY_SPLIT));
    }

    @Override
    protected List<ConnectCfg> transStr2List(String str) {
        List<ConnectCfg> list = new ArrayList<>();
        if (StringUtils.isNotBlank(str)) {
            String[] datas = str.split(ENTITY_SPLIT);
            for (int i = 0; i < datas.length; i++) {
                String[] temp = datas[i].split(ENTITY_ATTR_SPLIT);
                assert (temp.length == 6);
                list.add(new ConnectCfg(temp[0], temp[1], temp[2], temp[3], temp[4], temp[5]));
            }
        }
        return list;
    }


}
